package com.czmh.etc.onlinepubsys.services.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.dto.EtcAddressbookDto;
import com.czmh.etc.onlinepubsys.dto.EtcApplyDto;
import com.czmh.etc.onlinepubsys.dto.EtcIdcardDto;
import com.czmh.etc.onlinepubsys.dto.EtcVehiclelicenseDto;
import com.czmh.etc.onlinepubsys.dto.EtcYueSaveApplyReqDTO;
import com.czmh.etc.onlinepubsys.exceptions.EtcMsgException;
import com.czmh.etc.onlinepubsys.feign.newrun.YueClient;
import com.czmh.etc.onlinepubsys.feign.newrun.entity.yue.EtcYueApplyInfo;
import com.czmh.etc.onlinepubsys.feign.newrun.entity.yue.EtcYueBankCardInfo;
import com.czmh.etc.onlinepubsys.feign.newrun.entity.yue.EtcYueCarInfo;
import com.czmh.etc.onlinepubsys.feign.newrun.entity.yue.EtcYueShippingInfo;
import com.czmh.etc.onlinepubsys.json.JsonResult;
import com.czmh.etc.onlinepubsys.maper.EtcApplyMapper;
import com.czmh.etc.onlinepubsys.maper.EtcUserbankcardMapper;
import com.czmh.etc.onlinepubsys.model.EtcApply;
import com.czmh.etc.onlinepubsys.model.EtcUserbankcard;
import com.czmh.etc.onlinepubsys.respository.EtcApplyRepository;
import com.czmh.etc.onlinepubsys.respository.EtcUserbankcardRepository;
import com.czmh.etc.onlinepubsys.services.EtcInterpreterService;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.EtcUserInfoSevice;
import com.czmh.etc.onlinepubsys.services.YueService;
import com.czmh.etc.onlinepubsys.utils.DatetimeUtil;
import com.czmh.etc.onlinepubsys.utils.JsonResultUtil;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import com.czmh.etc.onlinepubsys.utils.wxpay.StringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName：YueServiceImpl
 * @Description：TODO
 * @Author： sevenchen.
 * @Date：2019/10/18 11:50.
 * @Version：1.0.0
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class YueServiceImpl implements YueService {
    @Autowired
    private EtcUserInfoSevice etcUserInfoSevice;
    @Autowired
    private EtcOrderService etcOrderService;
    @Autowired
    private EtcInterpreterService etcInterpreterService;
    @Autowired
    private YueClient yueClient;
    @Autowired
    private EtcUserbankcardRepository etcUserbankcardRepository;
    @Autowired
    private EtcUserbankcardMapper etcUserbankcardMapper;
    @Autowired
    private EtcApplyRepository etcApplyRepository;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private EtcApplyMapper etcApplyMapper;

    public JsonResult saveApplyInfo(String userId, EtcYueSaveApplyReqDTO saveApplyReqDTO) {
        EtcYueApplyInfo applyInfo = saveApplyReqDTO.getApplyInfo();
        EtcYueCarInfo carInfo = saveApplyReqDTO.getCarInfo();
        // 1.封装申请信息
        EtcApplyDto apply = new EtcApplyDto();
        // 设置申办渠道
        apply.setApply_channel(StringUtils.isEmpty(applyInfo.getApply_channel()) ? 1 : Integer.valueOf(applyInfo.getApply_channel()));
        apply.setApply_carlicencetyoe("0");
        // 设置车牌号码
        apply.setApply_carlicence(carInfo.getLicencePlate());
        apply.setApply_name(applyInfo.getApplyInfoName());
        apply.setApply_idcard(applyInfo.getIdCard());
        apply.setApply_carowneridcardfrontalphoto(applyInfo.getIdCardRightImg());
        apply.setApply_carowneridcardreversephoto(applyInfo.getIdCardWrongImg());
        apply.setApply_drivinglicencefrontalphoto(carInfo.getDrivingPermiRightImg());
        apply.setApply_drivinglicencereversephoto(carInfo.getDrivingPermiWrongImg());
        apply.setApply_carheadphoto("");
        apply.setApply_mannednum(carInfo.getHostNumberApproved());
        apply.setCardCatId(applyInfo.getCardCatId());
        apply.setApply_creditcard(applyInfo.getApply_creditcard());
        apply.setSerialnum(applyInfo.getSerialnum());
        // 2.封装用户身份证信息
        EtcIdcardDto idcard = new EtcIdcardDto();
        idcard.setAddress(applyInfo.getIdAddress());
        idcard.setNum(applyInfo.getIdCard());
        idcard.setEnd_date(DatetimeUtil.formatDate(applyInfo.getIdExpDate()));
        idcard.setStart_date(DatetimeUtil.formatDate(applyInfo.getIdEffDate()));
        idcard.setName(applyInfo.getApplyInfoName());
        // 3.封装行驶证信息
        EtcVehiclelicenseDto vehiclelicense = new EtcVehiclelicenseDto();
        vehiclelicense.setPlate_num(carInfo.getLicencePlate());
        vehiclelicense.setVehicle_type(carInfo.getCarType());
        vehiclelicense.setOwner(carInfo.getCarOwner());
        vehiclelicense.setUse_character(String.valueOf(carInfo.getCarUseType()));
        vehiclelicense.setModel(carInfo.getCarBrand());
        vehiclelicense.setVin("");
        vehiclelicense.setEngine_num(carInfo.getEngineNo());
        vehiclelicense.setRegister_date(DatetimeUtil.formatDate(carInfo.getRegisterDate()));
        vehiclelicense.setIssue_date(DatetimeUtil.formatDate(carInfo.getIssueDate()));
        vehiclelicense.setAppproved_passenger_capacity(carInfo.getHostNumberApproved());
        vehiclelicense.setFile_no(carInfo.getVehicleFrameNo());
        vehiclelicense.setGross_mass(carInfo.getGrossMass());
        vehiclelicense.setInspection_record("");
        vehiclelicense.setAddr(applyInfo.getIdAddress());
        EtcApply submitApplyInfo = etcUserInfoSevice.submitApplyInfo(userId, apply, idcard, vehiclelicense);
        Map<String, String> map = new HashMap<>();
        map.put("applyId", submitApplyInfo.getApply_id());
        // 调用纽润接口
        Object loginUserId = redisUtil.get(userId);
        if (loginUserId != null) {
            // 设置纽润的用户id
            saveApplyReqDTO.getApplyInfo().setLoginUserId(loginUserId.toString());
        }
        JsonResult jsonResult = yueClient.saveApplyInfo(saveApplyReqDTO);
        log.info("保存广东申请信息请求接口返回：" + JSON.toJSONString(jsonResult));
        if (!JsonResult.CODE_SUCCESS.equals(jsonResult.getCode().toString())) {
            throw new EtcMsgException(jsonResult.getCode(), jsonResult.getMessage());
        } else {
            if (jsonResult.getData() != null) {
                Map<String, Object> toMap = (HashMap<String, Object>) jsonResult.getData();
                String niurunApplyId = toMap.get("applyId").toString();
                map.put("niurunApplyId", niurunApplyId);
                EtcApply update = new EtcApply(submitApplyInfo.getApply_id());
                update.setNiurunApplyId(niurunApplyId);
                etcApplyMapper.update(update);
                return JsonResultUtil.toResult(map);
            } else {
                throw new EtcMsgException(jsonResult.getCode(), jsonResult.getMessage());
            }
        }
    }

    @Override
    public JsonResult addShippingInfo(String userId, EtcYueShippingInfo shippingInfo) {
        EtcAddressbookDto addressbookDto = new EtcAddressbookDto();
        addressbookDto.setUser_id(userId);
        addressbookDto.setApply_id(shippingInfo.getApplyId());
        addressbookDto.setAd_consignee(shippingInfo.getShippingName());
        addressbookDto.setAd_consigneephone(shippingInfo.getShippingMobile());
        addressbookDto.setAd_province(shippingInfo.getShippingProvince());
        addressbookDto.setAd_city(shippingInfo.getShippingCity());
        addressbookDto.setAd_region(shippingInfo.getShippingArea());
        addressbookDto.setAd_detailaddress(shippingInfo.getShippingAddress());
        String orderId = etcOrderService.submitaddrOrder(addressbookDto, "yue");
        Map<String, String> map = new HashMap<String, String>();
        map.put("orderId", orderId);
        // 设置参数请求纽润接口
        Object loginUserId = redisUtil.get(userId);
        if (loginUserId != null) {
            shippingInfo.setLoginUserId(loginUserId.toString());
        }
        shippingInfo.setApplyId(shippingInfo.getNiurunApplyId());
        shippingInfo.setNiurunApplyId(null);
        log.info("收货信息参数：" + JSON.toJSONString(shippingInfo));
        JsonResult jsonResult = yueClient.addShippingInfo(shippingInfo);
        if (!JsonResult.CODE_SUCCESS.equals(jsonResult.getCode().toString())) {
            throw new EtcMsgException(jsonResult.getCode(), jsonResult.getMessage());
        } else {
            return JsonResultUtil.toResult(map);
        }
    }

    @Override
    public JsonResult querySignType(String certNo) {
        JsonResult result = null;
        try {
            Assert.isTrue(StringUtil.isNotEmpty(certNo), "传入的身份证号为空！");
            log.info(String.format("[粤-接口调用] 根据证件号查询签约方式 certNo:\"%s\"", certNo));
            result = yueClient.querySignType(certNo);
            return result;
        }catch (Exception exp){
            log.warn(String.format("[粤-接口调用] 根据证件号查询签约方式报错。报错信息:\"%s\"", exp.getMessage()));
            exp.printStackTrace();
            result = new JsonResult();
            result.setCode(JsonResult.CODE_FAUILE);
            result.setStatus(false);
            result.setMessage(exp.getMessage());
        }

        return result;
    }

    @Override
    public JsonResult queryIssue(String mblNo, String plateColor, String plateNo) {
        JsonResult result = null;
        try {
            Assert.isTrue(StringUtil.isNotEmpty(plateColor), "传入的车牌颜色为空！");
            Assert.isTrue(StringUtil.isNotEmpty(plateNo), "传入的车牌号码为空！");
            log.info(String.format("[粤-接口调用] 查询车辆是否已办理粤通卡 telePhoneNo:\"%s\", plateColor:\"%s\", plateNo:\"%s\"", mblNo, plateColor, plateNo));
            result = yueClient.queryIssue(mblNo, plateColor, plateNo);
            return result;
        }catch (Exception exp){
            log.warn(String.format("[粤-接口调用] 查询车辆是否已办理粤通卡报错！报错信息:\"%s\"", exp.getMessage()));
            exp.printStackTrace();
            result = new JsonResult();
            result.setCode(JsonResult.CODE_FAUILE);
            result.setStatus(false);
            result.setMessage(exp.getMessage());
        }

        return result;
    }

    @Override
    public JsonResult bindAccount(String userId, EtcYueBankCardInfo bankCardInfo) {
        // 1.查询该银行卡是否已绑定
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("bankno", bankCardInfo.getBankNo());
        List<EtcUserbankcard> all = etcUserbankcardMapper.getAll(params);
        EtcUserbankcard userbankcard = new EtcUserbankcard(Sequence.getId());
        if (all.isEmpty()) {
            // 2.绑定银行卡
            userbankcard.setApply_id(bankCardInfo.getOtherApplyId());
            userbankcard.setBankcode(bankCardInfo.getBankCode());
            userbankcard.setBankmobile(bankCardInfo.getBankMobile());
            userbankcard.setBankname(bankCardInfo.getBankName());
            userbankcard.setIdaddress(bankCardInfo.getIdAddress());
            userbankcard.setIdcard(bankCardInfo.getIdCard());
            userbankcard.setIdcard_type(bankCardInfo.getIdCardType());
            userbankcard.setIdeffdate(bankCardInfo.getIdEffDate());
            userbankcard.setIdexpdate(bankCardInfo.getIdExpDate());
            userbankcard.setUsername(bankCardInfo.getUserName());
            userbankcard.setUser_id(userId);
            userbankcard.setBankno(bankCardInfo.getBankNo());
            userbankcard.setBankaccount(bankCardInfo.getBankAccount());
            userbankcard.setBankaccountcode(bankCardInfo.getBankAccountCode());
            etcUserbankcardRepository.save(userbankcard);
            // 更新申请状态为10-待审核
            params.clear();
            params.put("niurunApplyId", bankCardInfo.getApplyId());
            List<EtcApply> all2 = etcApplyMapper.getAll(params);
            if (!all2.isEmpty()) {
                EtcApply update = new EtcApply(all2.get(0).getApply_id());
                update.setApply_status(10);
                etcApplyMapper.update(update);
            }
        } else {
            return JsonResultUtil.toErrorResult("该银行卡已被绑定！");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("bank_id", userbankcard.getBank_id());
        // 调用纽润接口绑定银行卡
        Object loginUserId = redisUtil.get(userId);
        if (loginUserId != null) {
            bankCardInfo.setLoginUserId(loginUserId.toString());
        }
        log.info("请求绑卡接口参数：" + JSON.toJSONString(bankCardInfo));
        JsonResult jsonResult = yueClient.bindAccount(bankCardInfo);
        log.info("请求绑卡接口返回：" + JSON.toJSONString(jsonResult));
        if (!JsonResult.CODE_SUCCESS.equals(jsonResult.getCode().toString())) {
            throw new EtcMsgException(jsonResult.getCode(), jsonResult.getMessage());
        } else {
            return jsonResult;
        }
    }

    @Override
    public JsonResult checkOrder(String applyId) {
        JsonResult jsonResult = yueClient.checkOrder(applyId);
        if (JsonResult.CODE_SUCCESS.equals(jsonResult.getCode().toString())) {
            Map<String, Object> map = (Map<String, Object>) jsonResult.getData();
            List<EtcApply> list = new ArrayList<EtcApply>();
            EtcApply update = new EtcApply();
            update.setNiurunApplyId(applyId);
            update.setApply_status(Integer.valueOf(map.get("status").toString()));
            list.add(update);
            etcApplyMapper.batchUpdateApplyStatus(list);
        }
        return jsonResult;
    }
}
